<?php
/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2017/12/21
 * Time: 下午5:04
 */
class Courier extends CI_Controller{
    public function __construct(){
        parent::__construct();
        $this->load->database();
        $this->load->model('user_model');
        $this->load->model('box_model');
        $this->load->model('order_model');
        $this->load->model('courier_model');
        $this->load->library('form_validation');//加载表单验证类库
        $this->load->helper('json');
        $this->load->helper('common');
        $this->output->set_content_type('application/html;charset=utf-8');
    }

    // 快递员单子列表
    public function courier_service_list(){
        $requst = $_GET;
        if(!isset($requst['c_type']) || !$requst['c_type'] ){
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }
        $page = isset($requst['page'])?(int)$requst['page']:1;
        $psize = isset($requst['psize'])?(int)$requst['psize']:10;
        $courier_id =  isset($requst['courier_id']) ? $requst['courier_id'] : '';
        if($requst['c_type'] == 1){
            // 待接
            $re = $this->user_model->query_app_user_box('',[1],$page,$psize,'');
        }else{
            // 已接
            if(!$courier_id)
            {
                send_json(array('code'=>-1,'data'=>'','msg'=>"已接要传用户ID"));
            }
            $re = $this->user_model->query_app_user_box('',[2,3,4],$page,$psize,$courier_id);
        }
        send_json(array('code'=>0,'data'=>$re,'msg'=>""));
    }

    // 快递员接单
    public function courier_get_service(){
        // 查询单子当前的状态
        if($_GET['id'] && $_GET['courier_id'])
        {
            $id = $_GET['id'];
            $courier_id = $_GET['courier_id'];
            $user_box_info = $this->courier_model->get_app_user_box($id);
            if($user_box_info['status'] == 0){
                send_json(array('code'=>0,'data'=>'','msg'=>"已经取消召唤"));
            }
            if($user_box_info['status'] == 2 || $user_box_info['status'] == 3 || $user_box_info['status'] == 4)
            {
                send_json(array('code'=>0,'data'=>'','msg'=>"此单已经被接"));
            }
            if($user_box_info['status'] == 1)
            {
                $bool=$this->db->where(array("id"=>$id))->update('app_user_box',array("status"=>2,"courier_id"=>$courier_id));
                if($bool){
                    send_json(array('code'=>0,'data'=>'','msg'=>"接单成功"));
                }else{
                    send_json(array('code'=>-1,'data'=>'','msg'=>"接单失败"));
                }
            }
        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }

    }

    // 身份证保存
    function save_personal_info(){
        $post = $this->input->post();
        if($post['id'] && $post['id_number'] && $post['front_pic'] && $post['back_pic']){
            if(!isCreditNo($post['id_number']))
            {
                send_json(array('code'=>-1,'data'=>'','msg'=>"请输入正确的身份证号码"));
            }
            $bool=$this->db->where(array("id"=>$post['id']))->update('app_courier',array("id_number"=>$post['id_number'],"front_pic"=>$post['front_pic'],"back_pic"=>$post['back_pic']));
            if($bool){
                send_json(array('code'=>0,'data'=>'','msg'=>"保存成功"));
            }else{
                send_json(array('code'=>-1,'data'=>'','msg'=>"保存失败"));
            }

        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }
    }

    // 保存备注
    function save_remark(){
        $post = $this->input->post();
        if($post['id'] && $post['remark']){
            $bool=$this->db->where(array("id"=>$post['id']))->update('app_courier',array("remark"=>$post['remark']));
            if($bool){
                send_json(array('code'=>0,'data'=>'','msg'=>"保存成功"));
            }else{
                send_json(array('code'=>-1,'data'=>'','msg'=>"保存失败"));
            }

        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }
    }

    // 保存物流编号
    function save_bn(){
        $post = $this->input->post();
        if($post['id'] && $post['bn']){
            $bool=$this->db->where(array("id"=>$post['id']))->update('app_courier',array("bn"=>$post['bn']));
            if($bool){
                send_json(array('code'=>0,'data'=>'','msg'=>"保存成功"));
            }else{
                send_json(array('code'=>-1,'data'=>'','msg'=>"保存失败"));
            }

        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }
    }

    // 保存点部代码
    function save_code(){
        $post = $this->input->post();
        if($post['id'] && $post['code']){
            $bool=$this->db->where(array("id"=>$post['id']))->update('app_courier',array("code"=>$post['code']));
            if($bool){
                send_json(array('code'=>0,'data'=>'','msg'=>"保存成功"));
            }else{
                send_json(array('code'=>-1,'data'=>'','msg'=>"保存失败"));
            }

        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }
    }

    // 保存真实姓名
    function save_real_name(){
        $post = $this->input->post();
        if($post['id'] && $post['real_name']){
            $bool=$this->db->where(array("id"=>$post['id']))->update('app_courier',array("real_name"=>$post['real_name']));
            if($bool){
                send_json(array('code'=>0,'data'=>'','msg'=>"保存成功"));
            }else{
                send_json(array('code'=>-1,'data'=>'','msg'=>"保存失败"));
            }

        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }
    }

    // 保存快递公司
    function save_company(){
        $post = $this->input->post();
        if($post['id'] && $post['company']){
            $bool=$this->db->where(array("id"=>$post['id']))->update('app_courier',array("company"=>$post['company']));
            if($bool){
                send_json(array('code'=>0,'data'=>'','msg'=>"保存成功"));
            }else{
                send_json(array('code'=>-1,'data'=>'','msg'=>"保存失败"));
            }

        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }
    }

    // 返回所有快递公司
    function all_company_list()
    {
        send_json(array('code'=>0,'data'=>array('company_list'=>['圆通','顺丰','EMS']),'msg'=>""));
    }

    // 查询快递员信息
    function query_courier_info()
    {
        if($_GET['id'])
        {
            $info = $this->courier_model->query_courier_info($_GET['id']);
            send_json(array('code'=>0,'data'=>$info,'msg'=>"成功"));
        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }

    }

    // 快递员扫码箱子 同步订单
    function update_order_courier()
    {
        if($_POST['box_bn'] && $_POST['courier_id']){
            $info = $this->box_model->query_box_by_bn($_POST['box_bn']);
            if(!$info){
                send_json(array('code'=>-1,'data'=>'','msg'=>"这个箱子的编号不存在"));
            }
            $box_id = $info['id'];
            $order_list = $this->order_model->query_sending_order([1],'','',$box_id,1,1);
            if(!$order_list)
            {
                send_json(array('code'=>-1,'data'=>'','msg'=>"没有进行中的订单"));
            }
            $order_id = $order_list[0]['id'];
            $this->db->trans_begin();
            $bool1=$this->db->where(array("id"=>$order_id))->update('app_order',array("courier_id"=>$_POST['courier_id']));
            // 箱子归属改变
            $bool2=$this->db->where(array("id"=>$box_id))->update('app_box',array("use_status"=>2));
            // 快递员和箱子关系入库
//            $data_arr['box_id'] = $box_id;
//            $data_arr['courier_id'] = $_POST['courier_id'];
//            $data_arr['status'] = 1;
//            $data_arr['created_at'] = date("Y-m-d H:i:s");
//            $this->db->insert("app_courier_box",$data_arr);
            $this->courier_model->update_app_courier_box('1',$box_id,$_POST['courier_id']);
            if($bool1 && $bool2){
                $this->db->trans_commit();
                $order_info = $this->order_model->query_order_info($order_id);
                send_json(array('code'=>0,'data'=>array('order_info'=>$order_info),'msg'=>"订单同步成功"));
            }else{
                $this->db->trans_rollback();
                send_json(array('code'=>-1,'data'=>'','msg'=>"订单同步失败"));
            }
        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }
    }

    /**  验证短信验证码
     * @param string $tel 手机号
     * @param string $code 输入验证码
     * @return bool
     */
    function confirm_code_gerenal($tel="",$code=""){
        session_id($this->config->item("code_session_id"));
        session_start();
        $rs = isset($_SESSION[$tel."code"]) ? $_SESSION[$tel."code"] : '';
        if($rs){
            $data = json_decode($rs,true);
            $minute=floor((time()-strtotime($data['time']))%86400/60);
            if($minute>5){
                send_json(array('code'=>-1,'data'=>'','msg'=>"此验证码已超过5分钟,已失效"));
            }
            if($data['code'] == $code){
                return true;
            }else{
                send_json(array('code'=>-1,'data'=>'','msg'=>"验证码错误"));
            }
        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"此手机没有发送验证码"));
        }
    }

    // 保存快递员手机号
    function save_courier_tel(){
        $post = $this->input->post();
        if($post['tel'] && $post['code'] && $post['uid'])
        {
            // 手机号码校验
            if(!is_mobile($post['tel'])){
                send_json(array('code'=>-1,'data'=>'','msg'=>"请输入正确的手机号码"));
            }
            // 校验验证码
            $this->confirm_code_gerenal($post['tel'],$post['code']);
            // 数据
            $bool=$this->db->where(array("id"=>$post['uid']))->update('app_courier',array("tel"=>$post['tel']));
            if($bool)
            {
                send_json(array('code'=>0,'data'=>'','msg'=>"保存成功"));
            }else{
                send_json(array('code'=>-1,'data'=>'','msg'=>"保存失败"));
            }

        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }

    }

    // 快递人员输入物流单号
    function update_order_tracking_number(){
        $post = $this->input->post();
        if($post['tracking_number'] && $post['courier_id'] && $post['order_id']){
            $sql = "select courier_id from app_order where id = ".$post['order_id'];
            $order_info = $this->db->query($sql)->row_array();
            if($order_info && $order_info['courier_id']==$post['courier_id']){
                $bool=$this->db->where(array("id"=>$post['order_id']))->update('app_order',array("tracking_number"=>$_POST['tracking_number']));
                if($bool){
                    send_json(array('code'=>0,'data'=>'','msg'=>"保存成功"));
                }else{
                    send_json(array('code'=>-1,'data'=>'','msg'=>"保存失败"));
                }
            }else{
                send_json(array('code'=>-1,'data'=>'','msg'=>"该快递员没有权限"));
            }
        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }
    }

    // 上传图片
    function upload_image(){
        $post = $this->input->post();
        if($post['id'] && $_FILES['pic']['name']){
            $this->load->library('FileUpload','','mylib');
            $up = $this->mylib;
//            echo $this->config->item("upload_path");exit;
            $up->set("path",$this->config->item("upload_path"));
            $up->set("maxsize",2000000); //kb
            $up->set("allowtype",array("gif","png","jpg","jpeg"));//可以是"doc"、"docx"、"xls"、"xlsx"、"csv"和"txt"等文件，注意设置其文件大小
            $up->set("israndname",true);//true:由系统命名；false：保留原文件名

            //使用对象中的upload方法，上传文件，方法需要传一个上传表单的名字name：pic
            //如果成功返回true，失败返回false

            if($up->upload("pic")){
                $upd['id'] = $post['id'];
                $path = $up->getFileName();
                if ($path){
                    $pic_path = $this->config->item("upload_url").$path;
                    send_json(array('code'=>0,'data'=>array('pic_path'=>$pic_path,'pic_path_name'=>'/uploads/'.$path),'msg'=>"上传成功"));
                }else{
                    send_json(array('code'=>0,'data'=>'','msg'=>"上传失败"));
                }

            }else{
                $msg = "上传失败". $up->getErrorMsg().'路径是：'.$up->getPath();
                send_json(array('code'=>0,'data'=>'','msg'=>$msg));
            }
        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }

    }

    // 快递员获取箱子
    function get_box(){
        if($_POST['uid'] && $_POST['box_bn']){
            $info = $this->box_model->query_box_by_bn($_POST['box_bn']);
            if(!$info){
                send_json(array('code'=>-1,'data'=>'','msg'=>"这个箱子的编号不存在"));
            }
            if($info['use_status'] != 1){
                send_json(array('code'=>-1,'data'=>'','msg'=>"这个箱子无法使用或正在使用中"));
            }
            $box_id = $info['id'];
            $this->db->trans_begin();
            // 快递员和箱子关系入库
//            $data_arr['box_id'] = $box_id;
//            $data_arr['courier_id'] = $_POST['uid'];
//            $data_arr['status'] = 1;
//            $data_arr['created_at'] = date("Y-m-d H:i:s");
//            $this->db->insert("app_courier_box",$data_arr);
//            $insert_id = $this->db->insert_id();
            $insert_id = $this->courier_model->update_app_courier_box('1',$box_id,$_POST['uid']);
            $res2 = $this->db->where(array("id"=>$box_id))->update('app_box',array("use_status"=>2));

            if($insert_id && $res2)
            {
                $this->db->trans_commit();
                send_json(array('code'=>0,'data'=>'','msg'=>"获取成功"));
            }else{
                $this->db->trans_rollback();
                send_json(array('code'=>-1,'data'=>'','msg'=>"获取失败"));
            }

        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }
    }

    // 消息提醒列表
    function my_message_list(){
        if($_GET['uid']){
            $uid = $_GET['uid'];
            $sql = "select id,receiver_id,title,content,user_box_id,created_at from app_message_history WHERE receiver_type = 2 AND receiver_id = $uid ORDER BY id DESC ";
            $desc['page'] = isset($_GET['page'])?(int)$_GET['page']:1;
            $desc['psize'] = isset($_GET['psize'])?(int)$_GET['psize']:10;
            $limit_from = ($desc['page']-1)*$desc['psize'];
            $sql.=" limit ".$limit_from.",".$desc['psize'];
            $my_receiver_list = $this->db->query($sql)->result_array();
            send_json(array('code'=>0,'data'=>array('my_message_list'=>$my_receiver_list),'msg'=>"success"));
        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"缺少参数"));
        }
    }

    // 快递员结束订单
    function end_order(){
        $post = $this->input->post();
        if($post['box_bn'] && $post['uid']){

            // 箱子信息
            $box_info = $this->box_model->query_box_by_bn($post['box_bn']);
            // 修改订单状态
            $order_info = $this->order_model->query_order_by_box_id($box_info['id']);


            if($order_info['status'] == 1)
            {
                // 箱子状态
                $box_id = $order_info['box_id'];

                //开启事务
                $this->db->trans_begin();
                $res = $this->db->where(array("id"=>$box_id))->update('app_box',array("use_status"=>2));
                $res2 = $this->db->where(array("id"=>$order_info['id']))->update('app_order',array("status"=>2,"end_time"=>date("Y-m-d H:i:s")));
                // 如果是快递员送来的 算作结束 快递员和箱子关系跟新
                $this->courier_model->update_app_courier_box('1',$box_id,$post['uid']);
                // 计算价格
                $res3 = $this->order_model->deal_order_money($box_id,$order_info['id']);
//                // 重新插入当前快递员去送到桩点
//                $data_arr['user_id'] = $order_info['user_id'];
//                $data_arr['type'] = 2;
//                $data_arr['courier_id'] = $post['user_id'];
//                $data_arr['status'] = 3;
//                $data_arr['created'] = date("Y-m-d H:i:s");
//                $data_arr['address_id'] = '';
//                $this->db->insert("app_courier_box",$data_arr);

                if($res && $res2 && $res3)
                {
                    $this->db->trans_commit();
                    // 返回订单的详情
                    $order_info = $this->order_model->query_order_info($order_info['id']);
                    $box_info = $this->box_model->query_box_info($order_info['box_id']);
                    send_json(array('code'=>0,'data'=>array('order_info'=>$order_info,'box_info'=>$box_info),'msg'=>"订单已结束"));
                }else{
                    $this->db->trans_rollback();
                    send_json(array('code'=>0,'data'=>'','msg'=>"结束订单失败"));
                }

            }else{
                if($order_info['status'] == 0)
                {
                    send_json(array('code'=>-1,'data'=>'','msg'=>"订单已取消，无法结束订单"));
                }
                else if($order_info['status'] == 2)
                {
                    send_json(array('code'=>-1,'data'=>'','msg'=>"订单已结束"));
                }
            }
        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"缺少参数"));
        }
    }


    // 快递员归还箱子
    function back_box(){
            if($_POST['uid'] && $_POST['box_bn']){
                $info = $this->box_model->query_box_by_bn($_POST['box_bn']);
                if(!$info){
                    send_json(array('code'=>-1,'data'=>'','msg'=>"这个箱子的编号不存在"));
                }
                $box_id = $info['id'];

                $box_info = $this->box_model->query_box_detail($_POST['box_bn']);
                $box_latitude = $box_info['latitude'];
                $box_longitude = $box_info['longitude'];


                // 校验位置信息
                $stake_list = $this->box_model->query_stake_list();
                $distance_standard = 100;
                $flag = 0;
                $stake_info = '';
                foreach ($stake_list as $sl){
                    // 纬度
                    $latitude = $sl['latitude'];
                    // 经度
                    $longitude = $sl['longitude'];
                    $distance = distanceBetween($latitude,$longitude,$box_latitude,$box_longitude);
                    if($distance<$distance_standard){
                        $flag = 1;
                        $stake_info = $sl;
                        break;
                    }
                }
                if(!$flag){
                    send_json(array('code'=>-1,'data'=>'','msg'=>"箱子没有在固定装范围内，无法放回箱子"));
                }
                $this->db->trans_begin();
                if($info['use_status'] != 4 && $info['use_status'] != 5)
                {
                    $res1 = $this->db->where(array("id"=>$box_id))->update('app_box',array("use_status"=>1,'stake_id'=>$stake_info['id']));
                }
//                $res2 = $this->db->where(array("box_id"=>$box_id,"status"=>1))->update('app_courier_box',array("status"=>0));
                $res2 = $this->courier_model->update_app_courier_box('0',$box_id,$_POST['uid']);

                if($res1 && $res2)
                {
                    $this->db->trans_commit();
                    send_json(array('code'=>0,'data'=>'','msg'=>"归还成功"));
                }else{
                    $this->db->trans_rollback();
                    send_json(array('code'=>-1,'data'=>'','msg'=>"归还失败"));
                }

            }else{
                send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
            }
    }

    // 申请服务完毕
    public function ask_for_service_end()
    {
        // 修改服务状态
        $post = $this->input->post();
        if($post['uid'] && $post['service_id'])
        {
            $user_box_info = $this->courier_model->get_app_user_box($post['service_id']);
            if(!$user_box_info)
            {
                send_json(array('code'=>-1,'data'=>'','msg'=>"服务不存在"));
            }
            if($user_box_info['status'] == 4){
                send_json(array('code'=>-1,'data'=>'','msg'=>"服务已经结束"));
            }
            if($user_box_info['courier_id'] != $post['uid'])
            {
                send_json(array('code'=>-1,'data'=>'','msg'=>"无权操作"));
            }
            // 修改app_user_box 状态
            $bool=$this->db->where(array("id"=>$post['service_id']))->update('app_user_box',array("status"=>3));
            if($bool)
            {
                send_json(array('code'=>0,'data'=>'','msg'=>"success"));
            }else{
                send_json(array('code'=>-1,'data'=>'','msg'=>"修改失败"));
            }

        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }
    }

    // 快递员扫码开箱
    public function courier_sm()
    {
        if($_POST['uid'] && $_POST['box_bn']){
            $info = $this->box_model->query_box_by_bn($_POST['box_bn']);
            if(!$info){
                send_json(array('code'=>-1,'data'=>'','msg'=>"这个箱子的编号不存在"));
            }
            if($info['use_status'] == 1)
            {
                // 箱子未使用，快递员拿箱子
                send_json(array('code'=>0,'data'=>array('call_back_code'=>1,'call_back'=>'courier/get_box'),'msg'=>"success"));
            }
            // 箱子在用户手中
            if($info['use_status'] == 3)
            {
                // 查询订单状态
                $order_info = $this->order_model->query_order_by_box_id($info['id']);
                if($order_info['courier_id'])
                {
                    if($order_info['courier_id'] != $_POST['uid'])
                    {
                        send_json(array('code'=>-1,'data'=>'','msg'=>"你没有权限操作"));
                    }
                    // 结束订单
                    send_json(array('code'=>0,'data'=>array('call_back_code'=>3,'call_back'=>'courier/end_order'),'msg'=>"success"));
                }else{
                    // 同步订单时候用
                    send_json(array('code'=>0,'data'=>array('call_back_code'=>2,'call_back'=>'courier/update_order_courier'),'msg'=>"success"));
                }

            }
            // 箱子在快递员手中
            if($info['use_status'] == 2)
            {
                // 快递员运输途中开箱，不影响箱子的归属
                send_json(array('code'=>0,'data'=>array('call_back_code'=>4,'call_back'=>'box/courier_open_box_now'),'msg'=>"success"));
            }
            if($info['use_status'] == 4)
            {
                send_json(array('code'=>-1,'data'=>'','msg'=>"该箱子已经停止使用"));
            }
            if($info['use_status'] == 5)
            {
                send_json(array('code'=>-1,'data'=>'','msg'=>"该箱子已经被禁用"));
            }

        }else{
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }
    }

    // 快递员箱子列表
    public function courier_box_list()
    {
        $requst = $_GET;
        if(!check_param($requst,['courier_id']))
        {
            send_json(array('code'=>-1,'data'=>'','msg'=>"参数不全"));
        }
        if($requst['status'] == 1)
        {
            $status = '(1)';
        }else{
            $status = '(0,1)';
        }
        $page = isset($requst['page'])?(int)$requst['page']:1;
        $psize = isset($requst['psize'])?(int)$requst['psize']:10;
        $courier_id =  isset($requst['courier_id']) ? $requst['courier_id'] : '';
        $sql = "select acb.*,ab.box_bn,ab.type_id,ab.use_status from app_courier_box AS acb LEFT JOIN app_box AS ab ON acb.box_id = ab.id WHERE acb.courier_id = $courier_id AND acb.status in $status";

        // 分页
        $limit_from = ($page-1)*$psize;
        $sql.=" limit ".$limit_from.",".$psize;

        $res = $this->db->query($sql)->result_array();

        send_json(array('code'=>0,'data'=>$res,'msg'=>"success"));
    }




}